package com.foogui.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.foogui.constant.RedisConstant;
import com.foogui.dto.RedisData;
import com.foogui.dto.Result;
import com.foogui.entity.Shop;
import com.foogui.mapper.ShopMapper;
import com.foogui.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.foogui.utils.RedisConstants;

import com.foogui.utils.SimpleRedisLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {


    @Resource
    private RedissonClient redissonClient;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private SimpleRedisLock simpleRedisLock;
    /**
     * 查询-考虑到了缓存穿透和雪崩
     * @param id
     * @return
     */
    @Override
    public Result queryShopById(Long id) {
        //先从redis查
        String key= RedisConstant.CACHE_SHOP+id;
        String shopJSON = stringRedisTemplate.opsForValue().get(key);
        //避免缓存穿透
        if ("cache:through".equals(shopJSON)) {
            return Result.fail("为避免缓存穿透的做法");
        }
        if (StringUtils.isNotBlank(shopJSON)){
            //这里可以考虑更新ttl
            return Result.ok(JSONUtil.toBean(shopJSON,Shop.class));
        }
        //从数据库查
//        Shop shop = getById(id);
        //考虑到缓存雪崩
        Shop shop = queryWithMutex(id);
        if (shop==null){
            //缓存一个特殊值避免缓存穿透
            stringRedisTemplate.opsForValue().set(key,"cache:through",10L,TimeUnit.SECONDS);
            return Result.fail("店铺不存在");
        }
        //为TTL添加随机值避免缓存雪崩
        long extra = RandomUtil.randomLong(5);
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),30L+extra, TimeUnit.MINUTES);
        return Result.ok(shop);
    }

    /**
     * 查询-考虑缓存雪崩-互斥锁方案
     * @param id
     * @return
     */

    private Shop queryWithMutex(Long id) {
        //从缓存中自旋查
        String key= RedisConstant.CACHE_SHOP+id;
        String shopJSON = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(shopJSON)){
            //这里可以考虑更新ttl
            return JSONUtil.toBean(shopJSON,Shop.class);
        }
        Shop shop = null;
        //4.1 获取互斥锁
        String lockName = "shop:" + id;
        boolean isLock = simpleRedisLock.tryLock(lockName, 1L, TimeUnit.MINUTES);
        try {
            // 4.2 判断否获取成功
            if(!isLock){
                //4.3 失败，则休眠重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //4.4 成功，根据id查询数据库
            shop=getById(id);
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),30L, TimeUnit.MINUTES);
            return shop;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        finally {
            //7.释放互斥锁
            simpleRedisLock.unlock(lockName);
        }
    }

    public static final ExecutorService es= Executors.newFixedThreadPool(10);

    /**
     * 解决缓存击穿-逻辑过期
     * @param id
     * @return
     */
    public Shop queryWithLogicalExpire( Long id ){
        String key= RedisConstant.CACHE_SHOP+id;
        String shopJSON = stringRedisTemplate.opsForValue().get(key);
        // 判断hotkey是否存在,不存在说明对应的key就没有参加活动
        if (StringUtils.isBlank(shopJSON)){
            //这里可以考虑更新ttl
            return null;
        }
        //判断是否过期
        RedisData redisData = JSONUtil.toBean(shopJSON, RedisData.class);
        //注意JSONObject类型
        Object o = redisData.getData();
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        LocalDateTime now = LocalDateTime.now();
        if (expireTime.isAfter(now)){
            return shop;
        }
        String lockName="lock:shop:" + id;
        // boolean isLock = simpleRedisLock.tryLock(lockName, 30L, TimeUnit.SECONDS);
        RLock lock = redissonClient.getLock(lockName);
        boolean isLock = lock.tryLock();
        //获取锁开启异步线程去更新db
        if (isLock){
            try {
                es.submit(()->{
                    //模拟缓存重构的高延时
                    try {
                        TimeUnit.SECONDS.sleep(3);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    this.saveShop2Redis(id,30L);
                });
            } finally {

                lock.unlock();
                // simpleRedisLock.unlock(lockName);
            }
        }
        return shop;

    }

    private void saveShop2Redis(Long id, long expireSeconds) {
        Shop shop = getById(id);
        RedisData<Shop> data = new RedisData<>();

        data.setData(shop);
        data.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id, JSONUtil.toJsonStr(data));
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        if (shop==null || shop.getId()==null) return Result.fail("shop为null或者id为null");
        //先更新db
        updateById(shop);
        //再删除缓存
        stringRedisTemplate.delete(RedisConstant.CACHE_SHOP+shop.getId());
        return Result.ok();
    }
}
